package com.sqpoll.android;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.sqpoll.android.poll.HomePollListAdapter;
import com.sqpoll.android.poll.Poll;
import com.sqpoll.android.poll.PollCreateActivity;
import com.sqpoll.android.poll.PollDetailActivity;
import com.sqpoll.android.settings.SettingsActivity;

/**
 * The fragment for home.
 * 
 * @author Younggue Bae
 */
public class HomeFragment extends SherlockFragment {

	public static final String TAG = "HomeFragment";
	
	private ListView mListViewLeft;
	private ListView mListViewRight;
	private HomePollListAdapter mAdapterLeft;
	private HomePollListAdapter mAdapterRight;
	
	private char mWhichListViewTouched = ' ';

	int[] mLeftViewsHeights;
	int[] mRightViewsHeights;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}
	
	@Override
  public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.fragment_home, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_home, container, false);

		mListViewLeft = (ListView) view.findViewById(R.id.list_view_left);
		mListViewRight = (ListView) view.findViewById(R.id.list_view_right);
		
		List<Poll> leftItems = loadLeftItems();
		List<Poll> rightItems = loadRightItems();
		mAdapterLeft = new HomePollListAdapter(getActivity(), R.layout.list_item_poll_small, leftItems);
		mAdapterRight = new HomePollListAdapter(getActivity(), R.layout.list_item_poll_small, rightItems);
		mListViewLeft.setAdapter(mAdapterLeft);
		mListViewRight.setAdapter(mAdapterRight);

		mLeftViewsHeights = new int[leftItems.size()];
		mRightViewsHeights = new int[rightItems.size()];

		mListViewLeft.setOnTouchListener(mTouchListener);
		mListViewRight.setOnTouchListener(mTouchListener);
		mListViewLeft.setOnScrollListener(mScrollListener);
		mListViewRight.setOnScrollListener(mScrollListener);
		
		mListViewLeft.setOnItemClickListener(mLeftItemClickListener);
		mListViewRight.setOnItemClickListener(mRightItemClickListener);
		
		return view;
	}
	
	// Passing the touch event to the opposite list.
	OnTouchListener mTouchListener = new OnTouchListener() {
		boolean dispatched = false;

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (v.equals(mListViewLeft) && !dispatched) {
				mWhichListViewTouched = 'l';
				dispatched = true;
				mListViewRight.dispatchTouchEvent(event);
			} else if (v.equals(mListViewRight) && !dispatched) {
				mWhichListViewTouched = 'r';
				dispatched = true;
				mListViewLeft.dispatchTouchEvent(event);
			}

			dispatched = false;
			return false;
		}
	};
	
	/**
	 * Synchronizing scrolling. 
	 * Distance from the top of the first visible element opposite list: sum_heights
	 * (opposite invisible screens) - sum_heights(invisible screens) + distance from top of the first visible child
	 */
	OnScrollListener mScrollListener = new OnScrollListener() {

		@Override
		public void onScrollStateChanged(AbsListView v, int scrollState) {
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

			if (view.getChildAt(0) != null) {
				if (view.equals(mListViewLeft)) {
					mLeftViewsHeights[view.getFirstVisiblePosition()] = view.getChildAt(0).getHeight();

					int h = 0;
					for (int i = 0; i < mListViewRight.getFirstVisiblePosition(); i++) {
						h += mRightViewsHeights[i];
					}

					int hi = 0;
					for (int i = 0; i < mListViewLeft.getFirstVisiblePosition(); i++) {
						hi += mLeftViewsHeights[i];
					}

					int top = h - hi + view.getChildAt(0).getTop();
					mListViewRight.setSelectionFromTop(mListViewRight.getFirstVisiblePosition(), top);
				} else if (view.equals(mListViewRight)) {
					mRightViewsHeights[view.getFirstVisiblePosition()] = view.getChildAt(0).getHeight();

					int h = 0;
					for (int i = 0; i < mListViewLeft.getFirstVisiblePosition(); i++) {
						h += mLeftViewsHeights[i];
					}

					int hi = 0;
					for (int i = 0; i < mListViewRight.getFirstVisiblePosition(); i++) {
						hi += mRightViewsHeights[i];
					}

					int top = h - hi + view.getChildAt(0).getTop();
					mListViewLeft.setSelectionFromTop(mListViewLeft.getFirstVisiblePosition(), top);
				}

			}

		}
	};
	
	OnItemClickListener mLeftItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
			if (mWhichListViewTouched == 'l') {
				Poll currentItem = (Poll) mAdapterLeft.getItem(position);
				String question = currentItem.getQuestion();
				//Toast.makeText(getActivity(), "Selected : " + question, Toast.LENGTH_SHORT).show();
				
				Intent intent = new Intent(getActivity(), PollDetailActivity.class);
				intent.putExtra("id", "test");
				intent.putExtra("type", "group");
				intent.putExtra("question", question);
				startActivity(intent);			
			}
		}
	};
	
	OnItemClickListener mRightItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
			if (mWhichListViewTouched == 'r') {
				Poll currentItem = (Poll) mAdapterRight.getItem(position);
				String question = currentItem.getQuestion();
				//Toast.makeText(getActivity(), "Selected : " + question, Toast.LENGTH_SHORT).show();
				
				Intent intent = new Intent(getActivity(), PollDetailActivity.class);
				intent.putExtra("id", "test");
				intent.putExtra("type", "open");
				intent.putExtra("question", question);
				startActivity(intent);				
			}
		}
	};
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		Log.v(TAG, "Selected option item = " + item.getTitle());

		switch (item.getItemId()) {
		case R.id.menu_new_poll:
			//Toast.makeText(getActivity(), "Selected: New poll", Toast.LENGTH_SHORT).show();
			Intent intentPollCreate = new Intent(getActivity(), PollCreateActivity.class);
			getActivity().startActivity(intentPollCreate);
			break;
			
		case R.id.menu_my_polls_onwork:
			Toast.makeText(getActivity(), "Selected: My polls on work", Toast.LENGTH_SHORT).show();
			break;
			
		case R.id.menu_my_open_polls:
			Toast.makeText(getActivity(), "Selected: My open polls", Toast.LENGTH_SHORT).show();
			break;

		case R.id.menu_settings:
			//Toast.makeText(getActivity(), "Selected: Settings", Toast.LENGTH_SHORT).show();
			Intent intentSettings = new Intent(getActivity(), SettingsActivity.class);
			getActivity().startActivity(intentSettings);
			break;
		}

		return true;
	}

	private List<Poll> loadLeftItems() {
		Resources res = getResources();
		
		List<Poll> leftItems = new ArrayList<Poll>();
		
		Poll poll = new Poll();
		poll.setPollImage(res.getDrawable(R.drawable.ic_1));
		poll.setUsername("Sonya Cho_left1");
		poll.setCreateDate("1 day ago_left1");
		poll.setStatus("open");
		poll.setQuestion("Do you like this food?_left1");
		poll.setCommentCount(10);
		poll.setVoterCount(17);
		
		leftItems.add(poll);
		
		poll = new Poll();
		poll.setPollImage(res.getDrawable(R.drawable.ic_2));
		poll.setUsername("Younggue Bae_left2");
		poll.setCreateDate("06.07_left2");
		poll.setStatus("open");
		poll.setQuestion("Do you like this news?_left2");
		poll.setCommentCount(5);
		poll.setVoterCount(10);
		
		leftItems.add(poll);
		
		poll = new Poll();
		poll.setPollImage(res.getDrawable(R.drawable.ic_3));
		poll.setUsername("Sonya Cho_left3");
		poll.setCreateDate("1 day ago_left3");
		poll.setStatus("open");
		poll.setQuestion("Do you like this food?_left3");
		poll.setCommentCount(10);
		poll.setVoterCount(17);
		
		leftItems.add(poll);
		
		poll = new Poll();
		poll.setPollImage(res.getDrawable(R.drawable.ic_4));
		poll.setUsername("Sonya Cho_left4");
		poll.setCreateDate("1 day ago_left4");
		poll.setStatus("open");
		poll.setQuestion("Do you like this food?_left4");
		poll.setCommentCount(10);
		poll.setVoterCount(17);
		
		leftItems.add(poll);
		
		poll = new Poll();
		poll.setPollImage(res.getDrawable(R.drawable.ic_5));
		poll.setUsername("Sonya Cho_left5");
		poll.setCreateDate("1 day ago_left5");
		poll.setStatus("open");
		poll.setQuestion("Do you like this food?_left5");
		poll.setCommentCount(10);
		poll.setVoterCount(17);
		
		leftItems.add(poll);

		return leftItems;
	}
	
	private List<Poll> loadRightItems() {
		Resources res = getResources();
		
		List<Poll> rightItems = new ArrayList<Poll>();

		Poll poll = new Poll();
		poll.setPollImage(res.getDrawable(R.drawable.ic_6));
		poll.setUsername("Sonya Cho_right1");
		poll.setCreateDate("1 day ago_right1");
		poll.setStatus("open");
		poll.setQuestion("Do you like this food?_right1");
		poll.setCommentCount(10);
		poll.setVoterCount(17);
		
		rightItems.add(poll);
		
		poll = new Poll();
		poll.setPollImage(res.getDrawable(R.drawable.ic_7));
		poll.setUsername("Younggue Bae_right2");
		poll.setCreateDate("06.07_right2");
		poll.setStatus("open");
		poll.setQuestion("Do you like this news?_right2");
		poll.setCommentCount(5);
		poll.setVoterCount(10);
		
		rightItems.add(poll);
		
		poll = new Poll();
		poll.setPollImage(res.getDrawable(R.drawable.ic_8));
		poll.setUsername("Sonya Cho_right3");
		poll.setCreateDate("1 day ago_right3");
		poll.setStatus("open");
		poll.setQuestion("Do you like this food?_right3");
		poll.setCommentCount(10);
		poll.setVoterCount(17);
		
		rightItems.add(poll);
		
		poll = new Poll();
		poll.setPollImage(res.getDrawable(R.drawable.ic_9));
		poll.setUsername("Sonya Cho_right4");
		poll.setCreateDate("1 day ago_right4");
		poll.setStatus("open");
		poll.setQuestion("Do you like this food?_right4");
		poll.setCommentCount(10);
		poll.setVoterCount(17);
		
		rightItems.add(poll);
		
		poll = new Poll();
		poll.setPollImage(res.getDrawable(R.drawable.ic_10));
		poll.setUsername("Sonya Cho_right5");
		poll.setCreateDate("1 day ago_right5");
		poll.setStatus("open");
		poll.setQuestion("Do you like this food?_right5");
		poll.setCommentCount(10);
		poll.setVoterCount(17);
		
		rightItems.add(poll);
		
		return rightItems;
	}
	
}
